package com.leetcode.dataStruct.tree;

import com.leetcode.dataStruct.TreeNode;
import com.leetcode.math.ListNode;

import java.util.ArrayList;
import java.util.List;

public class SortedListToBST {
    public static void main(String[] args) {

    }

    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> nums = new ArrayList<>();
        ListNode cur = head;
        while (cur != null) {
            nums.add(cur.val);
            cur = cur.next;
        }
        return dfs(nums, 0, nums.size() - 1);
    }

    private TreeNode dfs(List<Integer> nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums.get(mid));
        root.left = dfs(nums, left, mid - 1);
        root.right = dfs(nums, mid + 1, right);
        return root;
    }
}
